package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: mengxiangzhong
 * @date: 2023/11/14 23:31
 * @DES:nacos操作类
 **/
@Service
public class NacosSupport {

    private final ConfigService configService;



    private NacosSupport(ConfigService configService) {
        this.configService = configService;
    }

    public static final String GROUP_ID = "SENTINEL_GROUP";
    public static final String RULE_PREFIX = "";

    public static final String FLOW_DATA_ID_POSTFIX = RULE_PREFIX + "-flow-rules";
    public static final String DEGRADE_DATA_ID_POSTFIX = RULE_PREFIX + "-degrade-rules";
    public static final String SYSTEM_DATA_ID_POSTFIX = RULE_PREFIX + "-system-rules";
    public static final String PARAM_FLOW_DATA_ID_POSTFIX = RULE_PREFIX + "-param-flow-rules";
    public static final String AUTHORITY_DATA_ID_POSTFIX = RULE_PREFIX + "-authority-rules";
    public static final String DASHBOARD_POSTFIX = "-dashboard";
    public static final String CLUSTER_MAP_DATA_ID_POSTFIX = RULE_PREFIX + "-cluster-map";

    public static final String API_DEFINITION_DATA_ID_POSTFIX = RULE_PREFIX + "-gw-api-groups";
    public static final String GATEWAY_FLOW_DATA_ID_POSTFIX = RULE_PREFIX + "-gw-flow-rules";

    public static final String TYPE = "json";


    /**
     * 将规则序列化成JSON文本，存储到Nacos-server中 (nacos持久化的数据库，可能是内存，可能是DB，一切看Nacos的持久化配置是否开启Mysql存储）
     *
     * @param app     应用名称
     * @param postfix 规则后缀
     * @param rules   规则对象
     * @throws NacosException 异常
     */
    public <T> void pushRule(String app, String postfix, List<T> rules) throws NacosException {
        if (StringUtil.isBlank(app)) {
            throw new RuntimeException("位置APP-NAME");
        }
        if (rules == null) {
            return;
        }

        // 规则消息推送至nacos
        String dataId = genDataId(app, postfix);
        configService.publishConfig(dataId, NacosSupport.GROUP_ID, JSON.toJSONString(rules), TYPE);

    }

    /**
     * 从Nacos server中查询响应规则，并将其反序列化成对应Rule实体
     *
     * @param appName 应用名称
     * @param postfix 规则后缀
     * @param clazz   类
     * @param <T>     泛型
     * @return 规则对象列表
     * @throws NacosException 异常
     */
    public <T> List<T> getRule(String appName, String postfix, Class<T> clazz) throws NacosException {
        String rules = configService.getConfig(genDataId(appName, postfix), NacosSupport.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return JSON.parseArray(rules, clazz);
    }

    private static String genDataId(String appName, String postfix) {
        return appName + postfix;
    }



}
